package cn.lger.config;

import cn.lger.entity.Role;
import cn.lger.security.CustomUserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * //允许在项目的本地方法中使用注解调用安全框架方法
 * //默认关闭状态
 * //@EnableGlobalMethodSecurity(prePostEnabled = true)
 * @author Pro
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        return new CustomUserDetailsServiceImpl();
    }

    @Override  
    protected void configure(AuthenticationManagerBuilder auth)  
            throws Exception {  
        auth    //配置验证时使用自定义Service，
                .userDetailsService(userDetailsService())
                .passwordEncoder(new BCryptPasswordEncoder());
    }  
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()//获取一个请求相关的认证器，用于配置请求认证
                //默认可访问/或/home
                .antMatchers("/", "/home").permitAll()
                //放行静态资源
                .antMatchers("/css/**","/js/**","/img/**","/vendors/**").permitAll()
                //要求{/user/**}的URL要有TEACHER或ADMIN角色
                .antMatchers("/user/**").hasAnyAuthority(Role.TEACHER.name(),Role.ADMIN.name())
                .anyRequest().permitAll()//其他任何请求放行
                .and()
            .formLogin()//获取表单认证配置
                //设置登录成功默认去当前路径
                .defaultSuccessUrl("/user/list")
                .permitAll()//表单可通过过滤
                .and()
            .logout()//注销当前用户
                .permitAll()
                .and()
            .csrf().disable();//设置csrf失效
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/js/**","/img/**","/vendors/**");
        super.configure(web);
    }
}
